package com.aaa.controller;

import com.aaa.entity.ReturnData;
import com.aaa.util.MyConstants;
import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2021/7/19 10:53
 * @description：所有controller的基础类
 * @description：所有controller的基础类
 * @description：所有controller的基础类
 * @modified By：
 * @version: 1.0
 */
public class BaseController extends HttpServlet {
    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description:通用的参数初始化方法
     * @create time: 2021/7/19 11:00
     * @param req
     * @param resp
     * @return java.util.Map<java.lang.String,java.lang.String>
     */
    public    Map<String,String> initParam(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {

        //设置编码格式
        req.setCharacterEncoding(MyConstants.CHARACTER_ENCODING);
        resp.setCharacterEncoding(MyConstants.CHARACTER_ENCODING);
        //设置响应数据类型
        resp.setContentType("application/json");
        //获取参数
        Enumeration<String> parameterNames = req.getParameterNames();
        //定义一个map集合封装所有的参数
        Map<String,String> map= new HashMap<>();
        while(parameterNames.hasMoreElements()){
            //获取参数名字
            String paramName = parameterNames.nextElement();
            //获取参数值
            String paramValue = req.getParameter(paramName);
            map.put(paramName,paramValue);
        }
        return map;
    }
    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 将回传的数据转换成json字符串,并相应给浏览器
     * @create time: 2021/7/19 11:02
     * @param returnData
     * @param resp
     * @return void
     */
    public  void  toJsonString(Object returnData,HttpServletResponse resp) throws IOException {

        //将回传的数据转换成json字符串
        String jsonString = JSON.toJSONStringWithDateFormat(returnData,"yyyy-MM-dd HH:mm:ss");
        //通过HttpServletResponse将json字符串响应给前端浏览器
        resp.getWriter().print(jsonString);
    }
    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 返回成功数据
     * @create time: 2021/7/19 17:01
     * @param returnData
     * @return com.aaa.entity.ReturnData
     */
    public ReturnData returnSuccess(ReturnData returnData){

        returnData.setCode(0);
        returnData.setMsg("操作成功");
        return returnData;
    }
    /**
     * @create by: Teacher陈（86521760@qq.com）
     * @description: 返回失败数据
     * @create time: 2021/7/19 17:01
     * @param returnData
     * @return com.aaa.entity.ReturnData
     */
    public ReturnData returnFail(ReturnData returnData){
        returnData.setCode(1);
        returnData.setMsg("操作失败");
        return returnData;
    }

}
